package com.wwwarehouse.usercenter.fragment.permission_recycle;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.CustomViewPagerInternal;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.custom_widget.time_pick.DateUtil;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tripartite_widget.viewindicator.CirclePageIndicator;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.adapter.SelectPermissionPagerAdapter;
import com.wwwarehouse.usercenter.bean.authoritydistribute.BatchAuthBean;
import com.wwwarehouse.usercenter.bean.authoritydistribute.PRSelectButtonBean;
import com.wwwarehouse.usercenter.bean.response.RetrieveUsersBean;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;
import com.wwwarehouse.usercenter.fragment.permissiondistribute.SetAuthorityTimeDialogFragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;


/**
 * 权限管理 -> 选择你要分配的人
 * Created by ShineF on 2017/9/25 0025.
 */
public class PRSelectPagerFragment extends BaseFragment implements ElasticScrollView.OnPullListener, CustomViewPagerInternal.OnPageChangeListener, PRSelectPagerContentFragment.OnButtonClickedListener {

    private StateLayout mStateLayout;
    private CustomViewPagerInternal mCustomPager;
    private CirclePageIndicator mCirclePager;
    private Button mDistributeBtn;
    private RelativeLayout mRlNoData;
    private static final int SIZE = 9;
    private static final int PAGE = 1;
    private List<Fragment> mFragmentList;
    private ElasticScrollView mCustomScrollView;
    private ArrayList<RetrieveUsersBean.ListBean> mSelectList;
    private BatchAuthBean mDataBean;
    private RetrieveUsersBean mOriginalData;
    private int mPos = 2;
    private String mSortUpDateTime = "update_time";
    private String mSortUpDateTimeDesc = "update_time desc";
    private String mSelectChooseSort = "update_time desc";
    private List<RetrieveUsersBean.ListBean> mOriginalList;
    private List<RetrieveUsersBean.ListBean> mDataList;
    private SelectPermissionPagerAdapter mViewPagerAdapter;
    private String mPRName;// = "xxx"
    private String mCardId;// = "52021102524651006"
    private String mBusinessId;// = "111111"
    private String mUserId;// = "19001"


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mPRName = bundle.getString("cardName");
            mCardId = bundle.getString("cardId");
            mBusinessId = bundle.getString("businessId");
        }
        // todo 待会儿解开这个注释
        mUserId = sp.getValue(Constant.sp_User_Id);
        mDataList = new ArrayList<>();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_select_distribution_pager_permission, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mStateLayout = $(R.id.state_layout);
        mCustomPager = $(R.id.custom_pager);
        mCirclePager = $(R.id.pager_indicator);
        mDistributeBtn = $(R.id.btn_distribute);
        mCustomScrollView = $(R.id.esv_view);
        mRlNoData = $(R.id.rl_no_data);
        mCustomScrollView.setVisibility(View.INVISIBLE);
        mDistributeBtn.setText(getResources().getString(R.string.user_pr_recycling));
        mDistributeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final SetAuthorityTimeDialogFragment dialogFragment = SetAuthorityTimeDialogFragment.newInstance();
                String message;
                if (mSelectList.size() > 1) {
                    message = String.format(getResources().getString(R.string.user_pr_recycling_msg_more), mSelectList.get(0).inviteeName, mSelectList.size(), mPRName);
                } else {
                    message = String.format(getResources().getString(R.string.user_pr_recycling_msg), mSelectList.get(0).inviteeName, mPRName);
                }
                dialogFragment.setTitle(getResources().getString(R.string.user_pr_sure))
                        .setMessage(message)
                        .setCancelText(getResources().getString(R.string.user_pr_consider))
                        .setConfirmText(getResources().getString(R.string.user_pr_sure_recycling))
                        .setOnCancelClickListener(new SetAuthorityTimeDialogFragment.onCancelClickListener() {
                            @Override
                            public void onCancelClick(View view, DialogFragment dialog) {

                                dialogFragment.dismiss();
                            }
                        })
                        .setOnConfirmClickListener(new SetAuthorityTimeDialogFragment.OnConfirmClickListener() {
                            @Override
                            public void onConfirmClick(View view) {
                                dialogFragment.dismiss();

                                Bundle bundle = new Bundle();
                                ArrayList<String> beUseIds = getBeUseIds();
                                bundle.putStringArrayList("beUseIds", beUseIds);
                                bundle.putString("cardId", mCardId);
                                bundle.putString("businessId", mBusinessId);
                                PRSuccessFragment fragment = new PRSuccessFragment();
                                fragment.setArguments(bundle);
                                PRSelectPagerFragment.this.popFragment();
                                pushFragment(fragment);
                            }
                        });
                dialogFragment.show(getFragmentManager(), "");
            }
        });
    }

    private ArrayList<String> getBeUseIds() {
        ArrayList<String> list = new ArrayList<>();
        for (RetrieveUsersBean.ListBean bean : mSelectList) {
            list.add(bean.inviteeId);
        }
        return list;
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof PRSelectPagerFragment) {
            mActivity.setTitle(getResources().getString(R.string.user_pr_select_recycling));
        }
    }

    @Override
    public void requestDatas() {
        mSelectList = new ArrayList<>();
        Bundle arguments = getArguments();
        if (arguments != null) {
            mDataBean = arguments.getParcelable(UserCenterConstant.KEY_BATCH_AUTH);
        }
        mDistributeBtn.setVisibility(View.GONE);
        mCustomScrollView.setOnPullListener(this);
        EventBus.getDefault().register(this);
        mStateLayout.showProgressView(true);
        mFragmentList = new ArrayList<>();
        requestParams(mSortUpDateTimeDesc, "");
        mStateLayout.setEmptyListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestParams(mSortUpDateTimeDesc, "");
            }
        });
        mStateLayout.setSystemListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestParams(mSortUpDateTimeDesc, "");
            }
        });
    }

    public void requestParams(String sort, String inviteName) {
        final Map<String, Object> map = new HashMap<>();
        List<String> inviteList = new ArrayList<>();
        map.put("businessId", mBusinessId);
        map.put("cardId", mCardId);
        map.put("userId", mUserId);
        loadData(UserCenterConstant.GET_RETRIEVE_USERES, map, 1);

    }

    public void loadData(String url, Map map, int what) {
        NoHttpUtils.httpPost(url, map, new NoHttpUtils.OnResponseListener() {
            @Override
            public void onSucceed(CommonClass commonClass, int i) {
                switch (i) {
                    case 1:
                        if ("0".equals(commonClass.getCode())) {
                            if (null != commonClass.getData()) {
                                mRlNoData.setVisibility(View.GONE);
                                mOriginalData = JSON.parseObject(commonClass.getData().toString(), RetrieveUsersBean.class);
                                if (mOriginalData.list == null || mOriginalData.list.size() == 0) {
                                    mRlNoData.setVisibility(View.VISIBLE);
                                } else {
                                    mOriginalList = mOriginalData.list;
                                    mDataList.addAll(mOriginalList);
                                    sortAsc(); // 接收时间从近到远排序
                                    setData();
                                }
                            } else {
                                mStateLayout.showSystemView(commonClass.getMsg(), false);
                            }
                        }
                        break;
                }


            }

            @Override
            public void onFailed(String s, int i) {

            }

            @Override
            public void onFinish(int i) {
                if (1 == i || 3 == i) {
                    dismissProgressDialog();
                }
            }
        }, what);
    }

    // 分页然后重新setAdapter
    private void divideGroup() {
        List<RetrieveUsersBean.ListBean> list = new ArrayList<>();
        // 分页
        mFragmentList.clear();
        for (int i = 0; i < mDataList.size(); i++) {
            list.add(mDataList.get(i));
            if (list.size() == 9 || i == mDataList.size() - 1) {
                List<RetrieveUsersBean.ListBean> perPageList = new ArrayList<>();
                perPageList.addAll(list);
                PRSelectPagerContentFragment fragment = new PRSelectPagerContentFragment();
                Bundle bundle = new Bundle();
                bundle.putSerializable(UserCenterConstant.KEY_SERIALIZABLE, (Serializable) perPageList);
                fragment.setArguments(bundle);
                fragment.setOnButtonClickedListener(this);
                mFragmentList.add(fragment);
            }
        }
        mCustomPager.removeAllViews();
        mViewPagerAdapter = new SelectPermissionPagerAdapter(getChildFragmentManager(), mFragmentList);
        mCustomPager.setAdapter(mViewPagerAdapter);
        mCirclePager.setViewPager(mCustomPager);
        mCustomPager.setOffscreenPageLimit(5);
        mCirclePager.requestLayout();
        mViewPagerAdapter.notifyDataSetChanged();
        refreshButtonState();
    }


    private void setData() {
        mFragmentList.clear();
        if (null != mOriginalData) {
            List<RetrieveUsersBean.ListBean> list = new ArrayList<>();
            // 分页
            for (int i = 0; i < mDataList.size(); i++) {
                list.add(mDataList.get(i));
                if (list.size() == 9 || i == mDataList.size() - 1) {
                    List<RetrieveUsersBean.ListBean> perPageList = new ArrayList<>();
                    perPageList.addAll(list);
                    PRSelectPagerContentFragment fragment = new PRSelectPagerContentFragment();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(UserCenterConstant.KEY_SERIALIZABLE, (Serializable) perPageList);
                    fragment.setArguments(bundle);
                    fragment.setOnButtonClickedListener(this);
                    mFragmentList.add(fragment);
                }
            }
            if (isAdded()) {
                mViewPagerAdapter = new SelectPermissionPagerAdapter(getChildFragmentManager(), mFragmentList);
                mCustomPager.setAdapter(mViewPagerAdapter);
                mCirclePager.setViewPager(mCustomPager);
                mCustomPager.setOffscreenPageLimit(5);
                mStateLayout.showContentView();
                mCustomScrollView.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void searchNoRealTimeClick(String text) {
        if (peekFragment() instanceof PRSelectPagerFragment) {
            List<RetrieveUsersBean.ListBean> tempList = new ArrayList<>();
            for (RetrieveUsersBean.ListBean bean : mDataList) {
                if (bean.inviteeName.contains(text)) {
                    tempList.add(bean);
                }
            }
            mDataList.clear();
            mDataList.addAll(tempList);
            divideGroup();
        }
    }

    @Override
    public void searchOnRealTimeClick(String text) {
        if (peekFragment() instanceof PRSelectPagerFragment) {
            if (TextUtils.isEmpty(text)) {
                mDataList.clear();
                mDataList.addAll(mOriginalList);
                divideGroup();
            }
        }
    }

    @Override
    public void sortClick(View anchor) {
        if (peekFragment() instanceof PRSelectPagerFragment) {
            showPopupWindow(anchor, mPos);
        }
    }

    public void showPopupWindow(View anchor, int pos) {
        PopUpUtils.showBubbleInviteSort(mActivity, anchor, pos, new PopUpUtils.OnChoiceListener() {
            @Override
            public void onChoice(int position) {
                PRSelectPagerFragment.this.mPos = position;
                switch (position) {
                    case 2: // 接收时间从近到远
                        sortAsc();
                        divideGroup();
                        break;
                    case 3: // 接收时间从远到近
                        sortDesc();
                        divideGroup();
                        break;
                    default:
                        break;
                }
            }
        }, null, getString(R.string.sort_type_receive_time_asc), getString(R.string.sort_type_receive_time_desc));
    }

    private void sortAsc() {
        Collections.sort(mDataList, new Comparator<RetrieveUsersBean.ListBean>() {
            @Override
            public int compare(RetrieveUsersBean.ListBean o1, RetrieveUsersBean.ListBean o2) {
                Date date1 = DateUtil.formatDateStr(o1.createTime, "yyyy-MM-dd HH:mm:ss");
                Date date2 = DateUtil.formatDateStr(o2.createTime, "yyyy-MM-dd HH:mm:ss");
                if (date1.after(date2)) {
                    return -1;
                } else if (date1.before(date2)) {
                    return 1;
                }
                return 0;
            }
        });
    }

    private void sortDesc() {
        Collections.sort(mDataList, new Comparator<RetrieveUsersBean.ListBean>() {
            @Override
            public int compare(RetrieveUsersBean.ListBean o1, RetrieveUsersBean.ListBean o2) {
                Date date1 = DateUtil.formatDateStr(o1.createTime, "yyyy-MM-dd HH:mm:ss");
                Date date2 = DateUtil.formatDateStr(o2.createTime, "yyyy-MM-dd HH:mm:ss");
                if (date1.after(date2)) {
                    return 1;
                } else if (date1.before(date2)) {
                    return -1;
                }
                return 0;
            }
        });
    }


    public void onEventMainThread(PRSelectButtonBean check) {
        if (check.getType().equals("isSelect") && peekFragment() instanceof PRSelectPagerFragment) {
//            hideSoftKeyBoard(mSearchEdt);
//			RetrieveUsersBean.ListBean data = check.getData();
//			if (mSelectList.contains(data)) {
//                mSelectList.remove(data);
//            } else {
//                mSelectList.add(data);
//            }
//            checkSelect();
        }
    }


    @Override
    public void onDownPull() {
        ((BaseCardDeskActivity) mActivity).downPull_4();
    }

    @Override
    public void onUpPull() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int i) {
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    public void checkSelect() {
        int i = 0;
        for (RetrieveUsersBean.ListBean bean : mSelectList) {
            if (bean.isSelected) {
                i++;
            }
        }
        if (i != 0) {
            mDistributeBtn.setVisibility(View.VISIBLE);
        } else {
            mDistributeBtn.setVisibility(View.GONE);
        }
    }

    @Override
    public void onButtonClicked() {
        refreshButtonState();
    }

    private void refreshButtonState() {
        mSelectList.clear();
        for (RetrieveUsersBean.ListBean bean : mDataList) {
            if (bean.isSelected) {
                mSelectList.add(bean);
            }
        }
        if (mSelectList.size() > 0) {
            mActivity.setTitle(String.format(getString(R.string.user_pr_select_recycling_count), mSelectList.size()));
        } else {
            mActivity.setTitle(getString(R.string.user_pr_select_recycling));
        }
        mDistributeBtn.setVisibility(mSelectList.size() > 0 ? View.VISIBLE : View.INVISIBLE);
    }
}
